<template>
  <div ref="login" class="login-container">
    <section>
      <div class="space-area">
        <el-carousel :interval="4000" arrow="hover">
          <el-carousel-item>
            <img src="@/assets/launch/login_1.png" height="400px" />
            <p>
              配合企业生产计划，帮助企业完成生产现场物料管理、生产进度实时监督，有效控制生产过程，提高生产效率
            </p>
          </el-carousel-item>
          <el-carousel-item>
            <img src="@/assets/launch/login_2.png" height="400px" />
            <p>
              配合企业生产计划，帮助企业完成生产现场物料管理、生产进度实时监督，有效控制生产过程，提高生产效率
            </p>
          </el-carousel-item>
          <el-carousel-item>
            <img src="@/assets/launch/login_3.png" height="400px" />
            <p>
              配合企业生产计划，帮助企业完成生产现场物料管理、生产进度实时监督，有效控制生产过程，提高生产效率
            </p>
          </el-carousel-item>
        </el-carousel>
        <!-- <img class="img-item" src="@/assets/launch/launch.jpg" width="120%" /> -->
      </div>
      <div class="form-area">
        <!-- <div class="logo">
          <img :src="logo" width="150" />
        </div> -->
        <!-- <div class="login-methods">
          <div class="method">
            <div class="prefix-icon">
              <i class="iconfont icon-saomaqiang" />
            </div>
            <div class="content">
              <h4>扫码枪登录</h4>
              <h6>使用扫码枪扫描员工铭牌一键登录</h6>
            </div>: string
            <div class="suffix-icon">
              <el-icon class="el-icon-caret-right" />
            </div>
          </div>
          <div class="method">
            <div class="prefix-icon">
              <el-icon class="el-icon-user" />
            </div>
            <div class="content">
              <h4>密码登录</h4>
              <h6>使用扫码枪扫描员工铭牌一键登录</h6>
            </div>
            <div class="suffix-icon">
              <el-icon class="el-icon-caret-right" />
            </div>
          </div>
        </div> -->
        <div class="main-form">
          <el-carousel
            ref="carousel"
            :initial-index="1"
            trigger="click"
            height="380"
            arrow="never"
            :autoplay="false"
            indicator-position="none"
          >
            <el-carousel-item>
              <el-form
                ref="loginForm"
                :model="loginForm"
                :rules="loginRules"
                class="login-form"
                autocomplete="on"
                label-position="left"
              >
                <div class="title-container">
                  <h3 class="title">维思生产管理系统</h3>
                </div>
                <el-form-item
                  prop="username"
                  :class="`form-item ${currentFocusInput === 'username' ? 'focused' : ''}`"
                >
                  <span class="svg-container">
                    <i class="el-icon-user" />
                  </span>
                  <el-input
                    ref="username"
                    v-model="loginForm.username"
                    placeholder="用户名"
                    name="username"
                    type="text"
                    tabindex="1"
                    autocomplete="on"
                    @focus="changeFocusStyle('username')"
                    @blur="onInputBlur"
                  />
                </el-form-item>
                <el-tooltip v-model="capsTooltip" content="大小写锁定" placement="right" manual>
                  <el-form-item
                    prop="password"
                    :class="`form-item ${currentFocusInput === 'password' ? 'focused' : ''}`"
                  >
                    <span class="svg-container">
                      <i class="el-icon-setting" />
                    </span>
                    <el-input
                      :key="passwordType"
                      ref="password"
                      v-model="loginForm.password"
                      :type="passwordType"
                      placeholder="密码"
                      name="password"
                      tabindex="2"
                      autocomplete="on"
                      @keyup.native="checkCapslock"
                      @keyup.enter.native="handleLogin"
                      @focus="changeFocusStyle('password')"
                      @blur="onInputBlur"
                    />
                    <span class="show-pwd" @click="showPwd">
                      <i :class="passwordType === 'password' ? 'el-icon-lock' : 'el-icon-view'" />
                    </span>
                  </el-form-item>
                </el-tooltip>
                <el-button
                  class="button-login"
                  :loading="loading"
                  type="primary"
                  style="width: 100%"
                  @click.native.prevent="handleLogin"
                  >登录</el-button
                >
              </el-form>
            </el-carousel-item>
            <el-carousel-item>
              <el-form
                ref="loginForm"
                :model="loginForm"
                :rules="loginRules"
                class="login-form"
                autocomplete="on"
                label-position="left"
              >
                <div class="title-container">
                  <h3 class="title">维思生产进度管理系统</h3>
                </div>
                <el-form-item
                  :class="`form-item ${currentFocusInput === 'scanner_username' ? 'focused' : ''}`"
                >
                  <span class="svg-container">
                    <i class="el-icon-user" />
                  </span>
                  <el-input
                    ref="scanner_username"
                    v-model="scanner_username"
                    placeholder="用户名"
                    type="password"
                    tabindex="1"
                    autocomplete="on"
                    @focus="changeFocusStyle('scanner_username')"
                    @keyup.enter.native="onkeyup"
                    @blur="onInputBlur"
                  />
                </el-form-item>
                <div class="button-container">
                  <el-button
                    class="button login"
                    :loading="loading"
                    type="primary"
                    @click.native.prevent="handleScannerLogin"
                  >
                    用户登录
                  </el-button>
                </div>
              </el-form>
            </el-carousel-item>
          </el-carousel>
          <!-- <div class="methods-list">
            <div
              :class="`method ${activeMode === 'password' ? 'active' : 'unactive'}`"
              @click="changeLoginMode('password')"
            >
              <el-icon class="el-icon-user" />
              密码登录
            </div>
            <div
              :class="`method ${activeMode === 'scanner' ? 'active' : 'unactive'}`"
              @click="changeLoginMode('scanner')"
            >
              <i class="iconfont icon-scanner" />
              扫码枪登录
            </div>
          </div> -->
        </div>
      </div>
      <div class="tool-list">
        <div class="icon" @click="changeTheme">
          <i :class="`iconfont icon-${active === 'light' ? 'day_mode' : 'night_mode'}`"></i>
          <span>{{ active === 'light' ? '日间' : '夜间' }}</span>
        </div>
        <div ref="serial" class="icon" @click="handleSerial">
          <i class="iconfont icon-com_port"></i>
          <span>串口</span>
        </div>
      </div>
    </section>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { Component, Watch, Ref } from 'vue-property-decorator'
import { validUsername } from '@/utils/validate'
import { Route } from 'vue-router'
import { serial } from '@/utils/navigator'
// import { loginBySerial } from '@/api/user'
import { Message } from 'element-ui'
type Dictionary<T> = { [key: string]: T }
type RouteQueryType = string | (string | null)[]
type ThemeMode = 'dark' | 'light'
const validateUsername = (rule: string, value: string, callback: (param?: Error) => void) => {
  if (!validUsername(value)) {
    callback(new Error('请输入正确的用户名'))
  } else {
    callback()
  }
}
const validatePassword = (rule: string, value: string, callback: (param?: Error) => void) => {
  if (value.length < 6) {
    callback(new Error('密码不能少于6个字符'))
  } else {
    callback()
  }
}
@Component
class Login extends Vue {
  // refs
  @Ref() readonly username!: HTMLInputElement
  @Ref() readonly password!: HTMLInputElement
  @Ref() readonly carousel!: any
  @Ref() readonly serial!: HTMLElement
  loginForm: Dictionary<string> = {
    username: '',
    password: ''
  }
  loginRules: Dictionary<
    {
      required: boolean
      trigger: string
      validator: (rule: string, value: string, callback: (param?: Error) => void) => void
    }[]
  > = {
    username: [{ required: true, trigger: 'blur', validator: validateUsername }],
    password: [{ required: true, trigger: 'blur', validator: validatePassword }]
  }
  scanner_username = ''
  passwordType = 'password'
  currentFocusInput = ''
  activeMode: 'scanner' | 'password' = 'scanner'
  capsTooltip = false
  loading = false
  showDialog = false
  redirect: RouteQueryType = ''
  otherQuery: Dictionary<RouteQueryType> = {}
  active: ThemeMode = 'light'
  logo = require(`@/assets/logo/${this.active}_logo.png`)
  // Watch Function
  @Watch('$route', { immediate: true })
  route_handler(route: Route): void {
    const query = route.query
    if (query) {
      this.redirect = query.redirect
      this.otherQuery = this.getOtherQuery(query)
    }
  }
  @Watch('active', { immediate: true })
  active_handler(newVal: ThemeMode) {
    this.logo = require(`@/assets/logo/${newVal}_logo.png`)
  }
  // 生命周期
  beforeMount() {
    // this.onElementEnter()
  }
  async mounted() {
    const { theme } = this.$store.state.theme
    this.active = theme
    if (this.loginForm.username === '') {
      const username = this.$refs.username as HTMLInputElement
      username.focus()
    } else if (this.loginForm.password === '') {
      const password = this.$refs.password as HTMLInputElement
      password.focus()
    }
    this.$nextTick(() => {
      // this.serial.dispatchEvent(new MouseEvent('click'))
    })
    // this.onElementEnter()
    this.$broadOn('onDirectiveCollected', (e: { fullPath: string; value: string }) => {
      const { fullPath, value } = e
      if (fullPath === this.$route.fullPath) {
        this.scanner_username = value
        this.handleScannerLogin()
      }
    })
  }
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  }
  // 方法
  onkeyup(e: any) {
    console.log(e)
  }
  checkCapslock(e: { key: string }) {
    const { key } = e
    this.capsTooltip = Boolean(key && key.length === 1 && key >= 'A' && key <= 'Z')
  }
  showPwd() {
    if (this.passwordType === 'password') {
      this.passwordType = ''
    } else {
      this.passwordType = 'password'
    }
    this.$nextTick(() => {
      const dom = this.$refs.password as HTMLInputElement
      dom.focus()
    })
  }
  handleLogin() {
    const loginForm = this.$refs.loginForm as any
    loginForm.validate((valid: boolean) => {
      if (valid) {
        this.loading = true
        this.$store
          .dispatch('user/login', this.loginForm)
          .then(() => {
            this.$router.push({
              path: (this.redirect as string) || '/',
              query: this.otherQuery
            })
            this.loading = false
          })
          .catch(() => {
            this.loading = false
          })
      } else {
        console.log('错误的提交!!')
        return false
      }
    })
  }
  getOtherQuery(query: Dictionary<RouteQueryType>) {
    return Object.keys(query).reduce((acc: Dictionary<RouteQueryType>, cur) => {
      if (cur !== 'redirect') {
        acc[cur] = query[cur]
      }
      return acc
    }, {})
  }
  changeFocusStyle(ref_name: string) {
    this.currentFocusInput = ref_name
  }
  onInputBlur() {
    this.currentFocusInput = ''
    this.capsTooltip = false
  }
  changeLoginMode(mode: any) {
    this.activeMode = mode
    // const carousel  = this.$refs.carousel as any
    this.carousel.setActiveItem(mode === 'password' ? 0 : 1)
  }
  handleScannerLogin() {
    this.loading = true
    this.$store
      .dispatch('user/login', { username: this.scanner_username })
      .then(() => {
        this.$router.push({
          path: (this.redirect as string) || '/',
          query: this.otherQuery
        })
        this.loading = false
      })
      .catch(() => {
        this.loading = false
      })
  }
  changeTheme() {
    const { theme } = this.$store.state.theme
    document.documentElement.setAttribute('data-theme', theme === 'dark' ? 'light' : 'dark')
    this.$store.dispatch('theme/changeTheme', {
      theme: theme === 'dark' ? 'light' : 'dark'
    })
    this.active = theme === 'dark' ? 'light' : 'dark'
  }
  async handleSerial() {
    // const navi = navigator as any
    // const ports = await navi.serial.getPorts()
    // // ports[0].addEventListener('connect', (e: any) => {
    // //   console.log(e)
    // // })
    // const port = await navi.serial.requestPort()
    // console.log(ports, port)
    // await port.open({ baudRate: 57600 })
    // port.addEventListener('disconnect', (e: any) => {
    //   console.log('v', e)
    // })
    // while (port.readable) {
    //   const reader = port.readable.getReader()
    //   try {
    //     while (true) {
    //       const { value, done } = await reader.read()
    //       console.log(value, done)
    //       if (done) {
    //         console.log('vvv')
    //         reader.releaseLock()
    //         break
    //       }
    //       console.log('zzz')
    //     }
    //   } catch (error) {
    //     console.log(error)
    //   }
    //   console.log(11)
    // }
    // ports.forEach(async (item: any) => {
    //   const info = await item.getInfo()
    //   const signal = await item.getSignals()
    //   console.log(info, signal)
    // })
    serial()
      .then(res => {
        console.log(res, this.serial)
        // loginBySerial({ array: [...(res as Uint8Array)] }).then(
        //   (res: AxiosResponse<Dictionary<string>, any>) => {
        //     this.scanner_username = res.data['login']
        //     this.handleScannerLogin()
        //   }
        // )
        this.serial.dispatchEvent(new MouseEvent('click'))
      })
      .catch(() => {
        Message({
          message: '串口连接失败，请检查周边是否有可用设备',
          type: 'warning'
        })
      })
    // serial().then(res => {
    //   console.log(res)
    // })
  }
}
export default Login
</script>

<style lang="less" scoped>
@media screen and (max-width: 1336px) {
  .login-container {
    section {
      .space-area {
        display: none;
      }
      .form-area {
        .main-form {
          /deep/.el-carousel {
            .el-carousel__container {
              .el-carousel__item {
                .login-form {
                  width: 60%;
                }
              }
            }
          }
          .methods-list {
            width: 60%;
          }
        }
      }
    }
  }
}
@media screen and (max-width: 756px) {
  .login-container {
    .form-area {
      .main-form {
        /deep/.el-carousel {
          .el-carousel__container {
            .el-carousel__item {
              .login-form {
                width: 60%;
                .title-container {
                  h3 {
                    font-size: 24px;
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>

<style lang="less" scoped>
@import '~@/styles/theme.less';

@heavier_bg_color: #2d88ff;
.login-container {
  box-sizing: border-box;
  width: 100%;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-size: cover;
  background-repeat: no-repeat;
  transition: all 0.5s ease;
  background-image: url('../../assets/launch/login_bg.svg');
  background-repeat: no-repeat;
  background-size: cover;
  #color(background-color, --primary-bg-color);
  section {
    position: relative;
    width: 70%;
    height: 80%;
    display: flex;
    align-items: flex-start;
    justify-content: flex-start;
    border-radius: 5px;
    overflow: hidden;
    transition: all 0.5s ease;
    backdrop-filter: blur(50px) brightness(1.1);
    z-index: 1;
    // #color(background-color, --module-bg-color);
    #shadow-color(2px, 4px, 8px, 0, --primary-shadow-color);
  }
  .space-area {
    width: 50%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 0 40px 40px 0;
    background: no-repeat;
    background-size: cover;
    background-position: left top;
    h4 {
      position: absolute;
      top: 0;
      left: 20px;
      display: flex;
      align-items: center;
      color: #ffffff;
      font-size: 18px;
    }
    h4::before {
      content: '';
      display: block;
      width: 10px;
      height: 10px;
      margin-right: 10px;
      border-radius: 50%;
      background-color: #ffffff;
    }
  }
  .form-area {
    position: relative;
    flex: 1;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    .main-form {
      width: 100%;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translateX(-50%) translateY(-50%);
      display: flex;
      flex-direction: column;
      align-items: center;
      /deep/.el-carousel {
        width: 100%;
        .el-carousel__container {
          height: 320px;
          .el-carousel__item {
            padding: 0;
          }
        }
        .svg-container {
          padding: 0;
          font-size: 14px;
          color: #415269;
        }
        .show-pwd {
          top: 0;
          right: 16px;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
    }
    .login-methods {
      width: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: space-between;
      .method {
        box-sizing: border-box;
        padding: 10px;
        width: 50%;
        height: 60px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border: solid 5px #2d3a4b;
        border-radius: 15px;
        .content {
          h4,
          h6 {
            color: #2d3a4b;
            margin: 0;
          }
          h6 {
            font-weight: 400;
          }
        }
      }
    }
    .login-form {
      box-sizing: border-box;
      padding: 40px;
      width: 70%;
      height: 80%;
      border: solid 1px;
      border-radius: 5px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      z-index: 2;
      transition: all 0.5s ease;
      #color(background-color, --module-bg-color);
      #color(border-color, --primary-border-color);
      #shadow-color(0, 8px, 16px, 0, --lighter-shadow-color);
      .title-container {
        position: relative;
        .title {
          font-size: 26px;
          #text-color(--primary-text-color);
          margin: 0px auto 40px auto;
          text-align: center;
          font-weight: bold;
        }
      }
      .svg-container {
        padding: 6px 5px 6px 15px;
        color: #2d3a4b;
        vertical-align: middle;
        width: 30px;
        display: inline-block;
      }
      /deep/.el-form-item {
        margin-bottom: 30px;
        .el-form-item__content {
          line-height: 30px;
          .el-form-item__error {
            top: 115%;
          }
        }
      }
      .button-container {
        display: flex;
        align-items: center;
        justify-content: space-between;
        .button {
          flex: 1;
          margin: 0 5px;
        }
      }
      .form-item {
        transition: all 0.5s ease;
      }
      .focused {
        border: solid 1px #62a6ff !important;
        box-shadow: 0 0 0 6px #d1e5ff;
        background-color: #f7f7f7;
      }
    }
    .login-form:hover {
      transform: translateY(-20px);
    }
    .methods-list {
      box-sizing: border-box;
      width: 50%;
      padding: 20px 0;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-top: solid 1px #e7e7e7;
      .method {
        box-sizing: border-box;
        padding: 10px 15px;
        font-size: 14px;
        border: solid 1px;
        color: #ffffff;
        transition: all 0.5s ease;
        cursor: pointer;
        #color(border-color, --lighter-blue-color);
        #color(background-color, --lighter-blue-color);
      }
      .active {
        #color(border-color, --primary-blue-color);
        #color(background-color, --primary-blue-color);
      }
      .active:hover {
        #color(background-color, --heavier-blue-color);
      }
      .unactive:hover {
        #color(color, --primary-blue-color);
        #color(border-color, --primary-blue-color);
        background-color: #dark[ @--primary-text-color];
      }
    }
  }
  .tool-list {
    position: absolute;
    top: 20px;
    right: 20px;
    display: flex;
    align-items: center;
    .icon {
      box-sizing: border-box;
      padding: 5px 8px;
      margin: 0 5px;
      display: flex;
      flex-direction: column;
      align-items: center;
      border-radius: 5px;
      transition: all 0.5s ease;
      #color(color, --primary-text-color);
      #color(background-color, --module-bg-color);
      #shadow-color(0, 0, 4px, 0, --primary-shadow-color);
      cursor: pointer;
      i {
        font-size: 20px;
      }
      .icon-day_mode {
        #color(color, --primary-red-color);
      }
      .icon-night_mode {
        #color(color, --primary-yellow-color);
      }
      span {
        font-size: 12px;
      }
    }
    .icon:hover {
      transform: translateY(-5px);
    }
  }
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: #2d3a4b;
    cursor: pointer;
    user-select: none;
  }
  /deep/.el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent !important;
      border: 0px;
      // -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      height: 47px;
      #color(color, --lighter-text-color);

      &:-webkit-autofill {
        transition: background-color 5000s ease-in-out 0s;
      }
    }
  }
  /deep/.el-form-item {
    border-radius: 5px;
    color: #454545;
    background: #e4eaf3;
    border: 1px solid rgba(255, 255, 255, 0.1);
    .el-form-item__content {
      display: flex;
      align-items: center;
    }
  }
  /deep/.el-carousel {
    width: 80%;
    height: 400px;
    .el-carousel__container {
      width: 100%;
      .el-carousel__item {
        box-sizing: border-box;
        padding: 0 40px;
        width: 100%;
        height: 400px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        border-radius: 10px;
      }
      .el-carousel__item {
        h2 {
          #color(color, --primary-text-color);
          font-size: 28px;
          margin: 0;
        }
        p {
          font-size: 14px;
          #color(color, --primary-text-color);
        }
      }
      .el-carousel__arrow {
        font-size: 14px;
        font-weight: 500;
        color: #2d3a4b;
        background-color: #ffffff;
        opacity: 0.8;
        #color(background-color, --primary-text-color);
        #color(color, --module-bg-color);
      }
    }
    .el-carousel__indicators {
      display: none;
      box-sizing: border-box;
      padding: 0 40px;
      bottom: 80px;
      .el-carousel__indicator {
        .el-carousel__button {
          width: 40px;
          height: 6px;
          border-radius: 5px;
        }
      }
    }
  }
}
</style>
